package com.example.hasee.zhcd.Activities.ChuanWu;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.hasee.zhcd.Adapters.MakePicListAdapter;
import com.example.hasee.zhcd.Adapters.PicfhjlAdapter;
import com.example.hasee.zhcd.Base.BaseActivity;
import com.example.hasee.zhcd.Bean.EventMsg;
import com.example.hasee.zhcd.R;
import com.example.hasee.zhcd.Util.ProgressDialogUtils;
import com.example.hasee.zhcd.View.NoScrollListView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

/**
 * Created by hasee on 2018/5/29.
 */

public class MakePicActivity extends BaseActivity {
    private RelativeLayout picLayout;
    private TextView title;
    private ImageView back;
    private ImageView home;
    private MakePicListAdapter adapter;
    private PicfhjlAdapter fh_adapter;
    private ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
    private ArrayList<HashMap<String, String>> fh_list = new ArrayList<HashMap<String, String>>();
    private NoScrollListView listView;
    private NoScrollListView fhjl_lv;
    private TextView dttitle;
    private TextView date;
    private int mYear;
    private int mMonth;
    private int mDay;
    private Bitmap bitmap;
    private String strShipYearNum;
    private LinearLayout fh_title;
    private Boolean fh_bol;

    @Override
    public int contentViewId() {
        return R.layout.activity_create_pictrue;
    }

    @Override
    public void set() {
        strShipYearNum = getIntent().getExtras().getString("fshipyearnumvcr");
        fh_bol = getIntent().getExtras().getBoolean("bol");
        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH) + 1;
        mDay = c.get(Calendar.DAY_OF_MONTH);
        title.setText("船舶在港动态");
        back.setOnClickListener(this);
        home.setImageResource(R.mipmap.baocuntupian);
        home.setOnClickListener(this);
        date.setText(mYear + "-" + mMonth + "-" + mDay);
        getPicInfo();
    }

    @Override
    public void init() {
        back = (ImageView) findViewById(R.id.back);
        home = (ImageView) findViewById(R.id.home);
        title = (TextView) findViewById(R.id.centertitle);
        picLayout = (RelativeLayout) findViewById(R.id.takepic);
        listView = (NoScrollListView) findViewById(R.id.dtlist);
        dttitle = (TextView) findViewById(R.id.dongtaititle);
        date = (TextView) findViewById(R.id.dateriqi);
        fhjl_lv = (NoScrollListView) findViewById(R.id.fhjl_lv);
        fh_title = (LinearLayout) findViewById(R.id.fh_title);
    }

    @Override
    public void getEventData(EventMsg msg) {
        switch (msg.getAction()) {
            case "Fail":
                ProgressDialogUtils.closeProgressDialog();
                Toast.makeText(MakePicActivity.this, "操作失败，请检查网络！", Toast.LENGTH_LONG).show();
                break;
            case "YWCX_lgcb_ssjl":
                ProgressDialogUtils.closeProgressDialog();
                try {
                    JSONObject json = new JSONObject(msg.getMsg());
                    String rspcode = json.getString("rspcode");
                    Log.e("rspcode", rspcode);
                    if ("0".equals(rspcode)) {
                        String rspmessage = json.getString("rspmessage");
                        if (!"".equals(rspmessage)) {
                            String arr[] = rspmessage.split("\\|");
                            dttitle.setText(arr[0]);
                            Log.e("长度", arr.length + "");
                        }
                        JSONArray data = json.getJSONArray("data");
                        for (int i = 0; i < data.length(); i++) {
                            HashMap<String, String> map = new HashMap<String, String>();
                            map.put("ftitle", data.getJSONObject(i).getString("ftitle"));
                            map.put("ftext", data.getJSONObject(i).getString("ftext"));
                            map.put("ftitle2", data.getJSONObject(i).getString("ftitle2"));
                            map.put("ftext2", data.getJSONObject(i).getString("ftext2"));
                            Log.e("ftext2", data.getJSONObject(i).getString("ftext2"));
                            list.add(map);
                        }
                        adapter = new MakePicListAdapter(MakePicActivity.this, list);
                        listView.setAdapter(adapter);
                    } else {
                        Toast.makeText(MakePicActivity.this, "暂无动态信息！", Toast.LENGTH_LONG).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (fh_bol) {
                    getPicfhjl();
                } else {
                    fh_title.setVisibility(View.GONE);
                    fhjl_lv.setVisibility(View.GONE);
                }
                break;
            case "YWCX_lgcb_fhjl":
                ProgressDialogUtils.closeProgressDialog();
                try {
                    JSONObject json = new JSONObject(msg.getMsg());
                    String rspcode = json.getString("rspcode");
                    if ("0".equals(rspcode)) {
                        JSONArray data = json.getJSONArray("data");
                        for (int i = 0; i < data.length(); i++) {
                            HashMap<String, String> map = new HashMap<String, String>();
                            map.put("fdate", data.getJSONObject(i).getString("fdate"));
                            map.put("fnote", data.getJSONObject(i).getString("fnote"));
                            fh_list.add(map);
                        }
                        fh_adapter = new PicfhjlAdapter(MakePicActivity.this, fh_list);
                        fhjl_lv.setAdapter(fh_adapter);
                    } else {
                        fh_title.setVisibility(View.GONE);
                        fhjl_lv.setVisibility(View.GONE);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    private void getPicInfo() {
        ProgressDialogUtils.createProgressDialog(MakePicActivity.this, "正在获取数据...");
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("strShipYearNum", strShipYearNum);
        httpUtils.get("YWCX_lgcb_ssjl", map, "YWCX_lgcb_ssjl");
    }

    private void getPicfhjl() {
        ProgressDialogUtils.createProgressDialog(MakePicActivity.this, "正在获取数据...");
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("strShipYearNum", strShipYearNum);
        httpUtils.get("YWCX_lgcb_fhjl", map, "YWCX_lgcb_fhjl");
    }

    Handler mhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            ProgressDialogUtils.closeProgressDialog();
            String obj = (String) msg.obj;
            switch (msg.what) {
                case 1:
                    Toast.makeText(MakePicActivity.this, obj, Toast.LENGTH_LONG).show();
                    break;
                case 2:
                    Toast.makeText(MakePicActivity.this, obj, Toast.LENGTH_LONG).show();
                    break;
                default:
                    break;
            }
        }
    };

    private Bitmap loadBitmapFromView(View v) {
        int w = v.getWidth();
        int h = v.getHeight();
        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);

        c.drawColor(Color.WHITE);
        /** 如果不设置canvas画布为白色，则生成透明 */

        v.layout(0, 0, w, h);
        v.draw(c);
        return bmp;
    }

    public void saveImageToGallery(Context context, Bitmap bmp) {
//        ProgressDialogUtils.createProgressDialog(MakePicActivity.this, "正在保存图片...");
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "ZhiHai");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
            Message message = new Message();
            message.what = 1;
            message.obj = "文件已保存至" + Environment.getExternalStorageDirectory() + "/ZhiHai_mis";
            mhandler.sendMessage(message);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Message message = new Message();
            message.what = 2;
            message.obj = "保存失败";
            mhandler.sendMessage(message);
        }
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getPath())));
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.home:
                bitmap = loadBitmapFromView(picLayout);
                ProgressDialogUtils.createProgressDialog(MakePicActivity.this, "正在保存图片...");
                new Thread(
                        new Runnable() {
                            @Override
                            public void run() {
                                saveImageToGallery(MakePicActivity.this, bitmap);
                            }
                        }
                ).start();

                break;
        }
    }
}
